Ext.define('Admin.view.page.operation.setting.SettingController', {
    extend: 'Ext.app.ViewController',

    alias: 'controller.group-menu',

    /**
     * 自定义宽高
     * 加载页面的基础数据到model中存储
     * @param {*} me 
     * @param {*} eOpts 
     */
    yeAfterrender(me, eOpts ){
        /*         
        //自定义宽高 -无需设置
        references.menuGridPanel.setWidth( 2/3 * allWidth )
        references.projectGridPanel.setWidth( 1/3 * allWidth )
        references.menuGridPanel.setHeight(allHeight)
        references.projectGridPanel.setHeight(allHeight)
         */
        // 将页面主要组件加入到data中缓存
        this.getViewModel().set('topComponent', me.ownerCt);
        this.getViewModel().set('pageComponent', me);
        // debugger
        //页面初始化
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let menuGridPanel = references.menuGridPanel
        // setTimeout(() => {
        //     menuGridPanel.getStore().reload({
        //         params: {
        //             groupType : 1,
        //             keyword : '',
        //         },
        //         // callback: function(records, operation, success) {
        //         //     console.log('Data loaded:', records);
        //         // }
        //     })
        // },1000)
        //如果存储再store中就要用获取stroe的model 来刷新界面;初始化时
        model.get('menuStore').reload({
            params: {
                groupType : 1,
                keyword : model.get('menuGridKeyword'),
            },
        })
        //如果是界面new的store;初始化时才可以通过这种通过组件去获取store的方式来刷新界面; 猜测原因应该是model中store实例化顺序不同
        //     menuGridPanel.getStore().reload({
        //         params: {
        //             groupType : 1,
        //             keyword : '',
        //         },
        //         // callback: function(records, operation, success) {
        //         //     console.log('Data loaded:', records);
        //         // }
        //     })
        // menuGridPanel.on('afterrender', function() {
        //     // 组件加载完成后执行的代码
        //     menuGridPanel.getStore().reload();
        // });
        // debugger
    },
    yeMenuGridAfterrender(me,opt){
    },
    yeProjectGridAfterrender(me,opt){
    },
    /**
     * 按钮点击
     */
    addMenuButton(me, event) {
        let model = this.getViewModel()
        // debugger
        let references = model.get('pageComponent').getReferences()
        let menuGridPanel = references.menuGridPanel
        let last = menuGridPanel.getStore().data.length + 1
        // 插入数据, 将光标锁定到新增的一行;
        let rec = Ext.create('Admin.model.operation.setting.Setting',{
            // id : null,
            parent_id : null,
            name : '',
            sort : last,
            type : '1', //1-菜单组 ，2 -任务组
        })
        // 生成唯一标识符
        const newId = Ext.data.identifier.Uuid.create().generate();
        // 设置新的 id
        rec.set('id', null);
        rec.set('clientId',newId)
        // let rec = {
        //     id : null,
        //     parent_id : null,
        //     name : '',
        //     sort : last,
        //     type : '1', //1-菜单组 ，2 -任务组
        // }
        menuGridPanel.getStore().insert(last, rec);
        menuGridPanel.getSelectionModel().selectRange(last - 1,last - 1);
        // 光标锁定到新增的数据第一个单元格上
        // let cellediting = menuGridPanel.getPlugins().filter(i => i.ptype == 'cellediting')[0]
        // cellediting.startEditByPosition({
        //     row: last - 1,
        //     column: 0
        // });
    },
    saveMenuButton(me, event) {
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let menuGridPanel = references.menuGridPanel
        let dataStore = menuGridPanel.getStore().getModifiedRecords()
        let data = []
        if(dataStore.length <= 0 ) {
            Ext.Msg.alert("提示", "保存失败,数据未发生更改");
            return
        }
        dataStore.forEach(item => {
            data.push(item.data)
        })
        // debugger
        Ext.Ajax.request({  
            method : 'POST',  
            url : '/ye/group/saveOrUpdate',  
            jsonData : data,
            success : function(response, config) {  
                var json = Ext.decode(response.responseText)
                if (json.success == true) {  
                    menuGridPanel.getStore().reload({
                        params: {
                            groupType : 1,
                            keyword : model.get('menuGridKeyword'),
                        },
                    })
                    Ext.Msg.alert("提示", '保存成功!')
                } else {  
                    Ext.Msg.alert('提示', '保存失败!')
                }  
            },  
            failure : function() {  
                Ext.Msg.alert('提示', '保存失败!')
            }  
        });          
    },
    deleteMenuButton(me, event) {
        let deleteFunc = () => {
            let model = this.getViewModel()
            let references = model.get('pageComponent').getReferences()
            let menuGridPanel = references.menuGridPanel
            // let dataSelected = menuGridPanel.getSelectionModel().getSelected()
            // dataSelected.each(item => {console.log(item)})
            // dataSelected.map
            let dataSelected = menuGridPanel.getSelectionModel().getSelection() 
            let datas = []
            if(dataSelected.length <= 0 ) {
                Ext.Msg.alert('提示', '未选择数据!')
                return
            }
            dataSelected.forEach(item => {
                if(!item.data.id) return 
                datas.push(item.data.id)
            })
            if(datas.length <= 0) {
                Ext.Msg.alert('提示', '数据还未保存无法删除!')
                return
            }
            Ext.Ajax.request({  
                method : 'GET',  
                url : '/ye/group/delete',  
                params : {  
                    ids : datas.join(','),
                    type : 'one',
                },  
                // jsonData : data,
                success : function(response, config) {  
                    var json = Ext.decode(response.responseText)
                    if (json.success == true) {  
                        menuGridPanel.getStore().reload({
                            params: {
                                groupType : 1,
                                keyword : model.get('menuGridKeyword'),
                            },
                        })
                        Ext.Msg.alert("提示", '删除成功!')
                    } else {  
                        Ext.Msg.alert('提示', '删除失败!')
                    }  
                },  
                failure : function() {  
                    Ext.Msg.alert('提示', '删除失败!')
                }  
            });
        }
        Ext.Msg.show({
		    title: '提示',
		    msg: '确认删除?',
		    width: 300,
		    buttons: Ext.Msg.OKCANCEL,
		    // animateTarget: tagetBtn,
		    icon: Ext.MessageBox.QUESTION,
		    fn: function(btn){
	    	   if (btn == 'ok') {
                    deleteFunc()
				}
		    }
		})
              

    },
    addMenuProjectButton(me, event) {
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let projectGridPanel = references.projectGridPanel
        let menuGridPanel = references.menuGridPanel
        let dataSelected = menuGridPanel.getSelectionModel().getSelection() 
        let datas = []
        if(dataSelected.length <= 0 ) {
            Ext.Msg.alert('提示', '未选择数据!')
            return
        }
        let last = projectGridPanel.getStore().data.length + 1
        // 插入数据, 将光标锁定到新增的一行;
        let rec = Ext.create('Admin.model.operation.setting.Setting',{
            id : null,
            group_id :  dataSelected[0].data.id,
            sort : last,
        })
        // 生成唯一标识符
        const newId = Ext.data.identifier.Uuid.create().generate();
        // 设置新的 id
        rec.set('id', null);
        rec.set('clientId',newId)
        projectGridPanel.getStore().insert(last, rec);
        projectGridPanel.getSelectionModel().selectRange(last - 1,last - 1);
    },
    saveMenuProjectButton(me, event) {
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let projectGridPanel = references.projectGridPanel
        let dataStore = projectGridPanel.getStore().getModifiedRecords()
        let data = []
        let idValid = []
        if(dataStore.length <= 0 ) {
            Ext.Msg.alert("提示", "保存失败,数据未发生更改");
            return
        }
        dataStore.forEach(item => {
            if(!item.data.id) {
                idValid.push(item.data)
            }
        })
        if(idValid.length > 0 ) {
            Ext.Msg.alert("提示", "存在没有选择具体项目的数据,请选择后再保存");
            return
        }
        dataStore.forEach(item => {
            data.push(item.data)
        })
        // debugger
        Ext.Ajax.request({  
            method : 'POST',  
            url : '/ye/group/saveOrUpdate',  
            jsonData : data,
            success : function(response, config) {  
                var json = Ext.decode(response.responseText)
                if (json.success == true) {  
                    if(model.get('dbRowDataCache')){
                        projectGridPanel.getStore().reload({
                            params: {
                                // group_id : dataSelected ? model.get('dbRowDataCache').get('name') : null,
                                group_id : model.get('dbRowDataCache').get('id'),
                                keyword : null
                            },
                        })
                    }
                    Ext.Msg.alert("提示", '保存成功!')
                } else {  
                    Ext.Msg.alert('提示', '保存失败!')
                }  
            },  
            failure : function() {  
                Ext.Msg.alert('提示', '保存失败!')
            }  
        });          
    },
    deleteMenuProjectButton(me, event) {
        let deleteFunc = () => {
            let model = this.getViewModel()
            let references = model.get('pageComponent').getReferences()
            let projectGridPanel = references.projectGridPanel
            // let dataSelected = menuGridPanel.getSelectionModel().getSelected()
            // dataSelected.each(item => {console.log(item)})
            // dataSelected.map
            let dataSelected = projectGridPanel.getSelectionModel().getSelection() 
            let datas = []
            if(dataSelected.length <= 0 ) {
                Ext.Msg.alert('提示', '未选择数据!')
                return
            }
            dataSelected.forEach(item => {
                if(!item.data.id) return 
                datas.push(item.data.id)
            })
            if(datas.length <= 0) {
                Ext.Msg.alert('提示', '数据还未保存无法删除!')
                return
            }
            Ext.Ajax.request({  
                method : 'GET',  
                url : '/ye/group/delete',  
                params : {  
                    ids : datas.join(','),
                    type : 'ship',
                },  
                // jsonData : data,
                success : function(response, config) {  
                    var json = Ext.decode(response.responseText)
                    if (json.success == true) {  
                        projectGridPanel.getStore().reload({
                            params: {
                                // group_id : dataSelected ? model.get('dbRowDataCache').get('name') : null,
                                group_id : model.get('dbRowDataCache').get('id'),
                                keyword : null
                            },
                        })
                        Ext.Msg.alert("提示", '删除成功!')
                    } else {  
                        Ext.Msg.alert('提示', '删除失败!')
                    }  
                },  
                failure : function() {  
                    Ext.Msg.alert('提示', '删除失败!')
                }  
            });
        }
        Ext.Msg.show({
		    title: '提示',
		    msg: '确认删除?',
		    width: 300,
		    buttons: Ext.Msg.OKCANCEL,
		    // animateTarget: tagetBtn,
		    icon: Ext.MessageBox.QUESTION,
		    fn: function(btn){
	    	   if (btn == 'ok') {
                    deleteFunc()
				}
		    }
		})
              

    },
    yeMenuGridRowclick(me, record, tr, rowIndex, e, eOpts ){
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        //将目前双击的格子加入到缓存中
        let menuGridPanel = references.menuGridPanel
        let dataSelected = menuGridPanel.getSelectionModel().getSelection() 
        if(dataSelected.length > 0 ) { 
            this.getViewModel().set('dbRowDataCache', dataSelected[0])
        }else{
            this.getViewModel().set('dbRowDataCache', null)
        }
        //加载子数据
        let projectGridPanel = references.projectGridPanel
        if(model.get('dbRowDataCache')){
            projectGridPanel.getStore().reload({
                params: {
                    // group_id : dataSelected ? model.get('dbRowDataCache').get('name') : null,
                    group_id : model.get('dbRowDataCache').get('id'),
                    keyword : null
                },
            })
        }
    },
    yeProjectNameEditorSelect(combo, record, i){
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let projectGridPanel = references.projectGridPanel
        let dataSelected = projectGridPanel.getSelectionModel().getSelection() 
        if(dataSelected.length > 0 ) { 
            // debugger
            // dataSelected[0].set('selectName', record.get('name'));
            dataSelected[0].set('selectName', record.get('name'));
            dataSelected[0].set('name', record.get('name'));
            dataSelected[0].set('id', record.get('id'));
        }
        // this.ownerCt().
        // var grid = combo.up('grid');
        // var selectedRecord = grid.getSelection()[0];
        // if (selectedRecord) {
        // selectedRecord.set('value', record.get('value'));
        // selectedRecord.set('displayName', record.get('displayName'));
        // }
    },
    yeProjectNameEditorBeforequery(queryPlan){ 
        // console.log('-------------')
        let model = this.getViewModel()
        let projectGridPanelNameComboBox =model.get('pageComponent').lookupReference('projectGridPanelNameComboBox')
        //展开下拉框
        projectGridPanelNameComboBox.expand()
        //关闭下拉框
        // projectGridPanelNameComboBox.collapse()
        if (queryPlan.query == '') {
            projectGridPanelNameComboBox.getStore().load({
                params: {
                  groupType : 2,
                //   group_id : dataSelected ? model.get('dbRowDataCache').get('name') : null,
                  keyword : null
                }
            });
            // 在用户未输入字符时返回false以阻止默认的查询行为
            return false;
          } else {
            // 在用户输入字符时手动触发查询
            projectGridPanelNameComboBox.getStore().load({
              params: {
                groupType : 2,
                keyword : queryPlan.query, // 将用户输入的字符作为查询参数传递给服务端
              }
            });
            return false; // 返回false以阻止默认的查询行为
          }
        // setTimeout(() => {
        //     me.getStore().load({
        //         params: {
        //             groupType : 2,
        //             keyword : '',
        //         },
        //     })
        // },1000)
        // me.getStore().load({
        //     params: {
        //         groupType : 2,
        //         keyword : '',
        //     },
        // })
    },
    yeProjectNameRenderer(value, metaData, record){
        // debugger
        return record.get('selectName') || value;
        // return record.get('name') || value;
    },
    menuGridPanelPagingToolbarBeforechange(me, page, eOpts){
        let model = this.getViewModel()
        me.getStore().getProxy().setExtraParams({
            groupType : 1,
            keyword : model.get('menuGridKeyword'),
            // page : page,
            // limit : 
        })
        return true
        // Ext.apply(eOpts, {
        //     groupType : 1,
        //     keyword : '',
        // });
    },
    projectGridPanelPagingToolbarBeforechange(me, page, eOpts){
        let model = this.getViewModel()
        me.getStore().getProxy().setExtraParams({
            group_id : model.get('dbRowDataCache').get('id'),
            keyword : null,
            // page : page,
            // limit : 
        })
        return true
        // Ext.apply(eOpts, {
        //     group_id : model.get('dbRowDataCache').get('id'),
        //     keyword : null
        // });
    },
    queryMenuButton(me, event) {
        let model = this.getViewModel()
        let references = model.get('pageComponent').getReferences()
        let menuGridPanel = references.menuGridPanel
        model.get('menuStore').reload({
            params: {
                groupType : 1,
                keyword : model.get('menuGridKeyword'),
                // page : 1,
            },
        })
    },
    yeProjectNameEditorAfterrender(combo) {
        // debugger

        // combo.getPicker().on('refresh', function() {
        //     var pagingToolbar = combo.getPicker().pagingToolbar;
        //     if (pagingToolbar && pagingToolbar.el) {
        //         pagingToolbar.el.dom.style.minWidth = 'auto';
        //     }
        // });
    }
});

